package com.apestech.api.condition.Step;

import com.apestech.api.query.XLSReadCallback;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.xml.condition.modul.ConditionStrategy;

public class StepXlsRead extends StepPubField {

    private ArrayCallback arrayCallback;

    public StepXlsRead(ConditionStrategy.Step step, SqlSession session) throws Exception {
        super(step, session);
    }

    public void setArrayCallback(ArrayCallback arrayCallback) {
        this.arrayCallback = arrayCallback;
    }

    @Override
    public void exec() throws Exception {
        JSONArray list = new JSONArray();
        ConditionStrategy.Step step=super.getStep();
        JSONObject input=super.getInput();
        JSONObject o=new JSONObject();
        SqlSession esession=getStepDb(super.getStep().getDb(), super.getSession());
        XLSReadCallback xLSReadCallback=new XLSReadCallback(){
            boolean read=false;
            @Override
            public JSONObject getHead(JSONObject head, String sheetName) throws Exception {
                return head;
            }
            @Override
            public JSONObject getRow(JSONObject row, int index) throws Exception {
                JSONObject m = new JSONObject();
                m.putAll(input);
                m.putAll(row);
                list.add(m);
                if(!read) {
                    o.putAll(row);
                    read=true;
                }
                if(arrayCallback!=null){
                    m=arrayCallback.getRow(m);
                }
                return m;
            }
        };
        esession.importXls(step.getId(), input.getString(step.getXlsReadFile()), input, xLSReadCallback);
        if(step.isAlldata()){
            o.put(step.getMutikey(), list);
        }
        closeSession(super.getSession(), esession);
        finiExec(o, step);
        step.setResultMap(o);
    }

}
